import router from './router'
import { getToken } from '@/utils/auth'
import { isPathMatch } from '@/utils/validate'

const whiteList = ['/login', '/test']

const isWhiteList = (path) => {
  return whiteList.some((pattern) => isPathMatch(pattern, path))
}

router.beforeEach((to, from, next) => {
  if (getToken()) {
    if (to.path === '/login') {
      next({ path: '/' })
    } else if (isWhiteList(to.path)) {
      next()
    } else {
      next()
    }
  } else {
    if (isWhiteList(to.path)) {
      // 在免登录白名单，直接进入
      next()
    } else {
      next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
      //     next({
      //       path: '/login',
      //       query: { redirect: to.fullPath }, // 记录原路径，登录后跳回
      //     })
    }
  }
})
